package com.culture.bootdemo.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;

import java.net.InetAddress;
import java.text.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author: wen
 * @date 2020/9/25
 * 生成唯一订单号
 */
@Slf4j
public class CreateOrderNoUtil {
    /**
     * 订单号生成
     **/
    private static ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai");
    private static final AtomicInteger SEQ = new AtomicInteger(1000);
    private static final DateTimeFormatter DF_FMT_PREFIX = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
    private volatile static String IP_SUFFIX = null;

    /**
     * 生成订单号 方法一：
     *
     * @return
     */
    public static String generateOrderNo() {
        LocalDateTime dataTime = LocalDateTime.now(ZONE_ID);
        if (SEQ.intValue() > 9990) {
            SEQ.getAndSet(1000);
        }
        return dataTime.format(DF_FMT_PREFIX) + getLocalIpSuffix() + SEQ.getAndIncrement();
    }

    /**
     * 生成订单号 方法二：
     *
     * @return
     */
    public static synchronized long genNdOrderId() {
        long orderId = -1L;
        StringBuffer sb = new StringBuffer();
        try {

            String uuid = UUID.randomUUID().toString();
            String localIp = InetAddress.getLocalHost().getHostAddress();
            String UUID = localIp + "$" + uuid;
            Random r = new Random();
            int iRandom = Math.abs(r.nextInt(100));
            //外单号首位固定为3,为避免和以前的外单订单号重复
            sb.append("3");
            sb.append(Math.abs(UUID.hashCode()));
            sb.append(iRandom);

            if (sb.length() < 14) {
                sb.append("12345678901234", 0, 14 - sb.length());
            }
            orderId = Long.parseLong(sb.toString().substring(0, 14));
        } catch (Exception e) {
            String errorMsg = "生成订单号错误";
            log.error(errorMsg);
            throw new RuntimeException(errorMsg);
        }

        return orderId;
    }


    /**
     * 服务部署多个节点的话，获取节点IP；单机可省略拼接该方法
     *
     * @return
     */
    private static String getLocalIpSuffix() {
        if (null != IP_SUFFIX) {
            return IP_SUFFIX;
        }
        try {
            synchronized (CreateOrderNoUtil.class) {
                if (null != IP_SUFFIX) {
                    return IP_SUFFIX;
                }
                InetAddress addr = InetAddress.getLocalHost();
                //  172.17.0.4  172.17.0.199 ,
                String hostAddress = addr.getHostAddress();
                if (null != hostAddress && hostAddress.length() > 4) {
                    String ipSuffix = hostAddress.trim().split("\\.")[3];
                    if (ipSuffix.length() == 2) {
                        IP_SUFFIX = ipSuffix;
                        return IP_SUFFIX;
                    }
                    ipSuffix = "0" + ipSuffix;
                    IP_SUFFIX = ipSuffix.substring(ipSuffix.length() - 2);
                    return IP_SUFFIX;
                }
                IP_SUFFIX = RandomUtils.nextInt(10, 20) + "";
                return IP_SUFFIX;
            }
        } catch (Exception e) {
            System.out.println("获取IP失败:" + e.getMessage());
            IP_SUFFIX = RandomUtils.nextInt(10, 20) + "";
            return IP_SUFFIX;
        }
    }


    private static final FieldPosition HELPER_POSITION = new FieldPosition(0);
    private static final Format DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmssS");
    private static final NumberFormat NUMBER_FORMAT = new DecimalFormat("0000");
    private static int seq = 0;

    public static synchronized String generateSequenceNo() {
        Calendar rightNow = Calendar.getInstance();
        StringBuffer sb = new StringBuffer();
        DATE_FORMAT.format(rightNow.getTime(), sb, HELPER_POSITION);
        NUMBER_FORMAT.format(seq, sb, HELPER_POSITION);
        if (seq == 9999) {
            seq = 0;
        } else {
            ++seq;
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        List<String> orderNos = Collections.synchronizedList(new ArrayList<String>());
        IntStream.range(0, 8000).parallel().forEach(i -> {
            orderNos.add(generateOrderNo());
        });

        List<String> filterOrderNos = orderNos.stream().distinct().collect(Collectors.toList());

        System.out.println("订单样例：" + orderNos.get(0));
        System.out.println("生成订单数：" + orderNos.size());
        System.out.println("过滤重复后订单数：" + filterOrderNos.size());
        System.out.println("重复订单数：" + (orderNos.size() - filterOrderNos.size()));

        System.out.println("方法二："+genNdOrderId());
        System.out.println("唯一值的一种"+generateSequenceNo());
    }
}
